package algorithm.leetcode.simple;

/*
 给定一个排序数组和一个目标值，在数组中找到目标值，并返回其索引。
 如果目标值不存在于数组中，返回它将会被按顺序插入的位置。
 */

/**
 * @author jack.wu
 * @version 1.0
 * @date 2020/9/28
 */
public class Question35 {

    public static void main(String[] args) {
        int[] nums = {1,3,5,6};
        Question35 question = new Question35();
        int index = question.searchInsert(nums, 3);
        System.out.println(index);
    }

    public int searchInsert(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] < target) {
                left = mid + 1;
            }else {
                right = mid -1;
            }
        }
        return left;
    }








    private int recursionSearch(int[] nums, int left, int right, int target) {
        if (left > right) {
            return -1;
        }
        int mid = (left + right) / 2;
        int num = nums[mid];
        if (target == num) {
            return mid;
        }else if (target < num) {
           return recursionSearch(nums, left, mid - 1, target);
        }else {
           return recursionSearch(nums, mid + 1, right, target);
        }

    }
}
